

from flask import (
    Blueprint,request, jsonify,session,make_response,send_from_directory
)
import os
from werkzeug.utils import secure_filename
import uuid


bp = Blueprint('uploadImg', __name__)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = 'D:/VUE/Git/Python/myflask/upload' # 定义上传目录

# 效验器
# 要求登录的装饰器
def login_required(func):
    def wrapper(*args, **kwargs):
        user_id = request.cookies.get('user_id',None)
        print(user_id)
        print(session)
        if user_id is None or user_id not in session or session[user_id] != user_id:
            response = make_response(jsonify({
            "msg": "请登录后操作",
            "code": 403
        }))
            response.status_code = 400  # 设置状态码为400
            return response
        return func(*args, **kwargs)
    return  wrapper

#文件上传
@login_required
@bp.route('/uploadImg',methods=('post',) ,endpoint='uploadImg')
def upload_img():
    BASE_URL = 'https://flask.passlink.cn/imgs/'  # 获取当前请求的域名，并构建基本URL
    if 'file' not in request.files:
        return '没有选择文件'
    file = request.files['file']
    if file.filename == '':
        return '没有选择文件'
    if file and allowed_file(file.filename): # 验证文件类型
        filename = secure_filename(file.filename)
        filename = str(uuid.uuid4()) + os.path.splitext(filename)[1]  # 使用uuid生成唯一文件名
        file_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(file_path) # 保存文件到指定目录
        file_url = BASE_URL+ filename  # 构建访问链接
        return jsonify({'code': 200, 'msg': '上传成功', 'data': {'url': file_url}})
    else:
        return '不支持该文件类型'

# 验证文件类型
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#文件访问
@bp.route('/imgs/<filename>', methods=['GET'])
def get_img(filename):
    if len(filename) < 100 and allowed_file(filename) and  len(filename) >5:
        return send_from_directory(UPLOAD_FOLDER,filename)
    else:
        return '请求失败'